<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Shop\Models\GoodsCategories;
use App\Modules\Shop\Models\Products;
use App\Modules\Shop\Models\ProductSpecifiction;
use App\Modules\Shop\Services\GoodsCategoriesService;
use App\Modules\Shop\Services\ProductsService;
use App\Modules\Shop\Services\ProductsSpecifictionService;
use App\Modules\Shop\Services\ShipFeeTemplateService;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Image;
use DB;

class ShopController extends Controller
{
    public function editGoods(Request $request)
    {

        return Admin::content(function (Content $content) use($request){
            $categories = GoodsCategoriesService::getAll();
            $ship_fee_temp = ShipFeeTemplateService::getAll();
            $goods_id = $request->input('goods_id','');
            $products_info=null;
            if($goods_id) {
                $products_info = ProductsService::getProductsDetail($goods_id);
                $products_info->product_specific;
                $detail_arr = explode(',',$products_info->detail);
                array_walk($detail_arr,function (&$item,$key){
                    $item = "<p><img src='".$item."' style='max-width:100%' /></p>";
                });
                $products_info->detail = implode('',$detail_arr);
            }
            $content->body(view("shop.edit_goods",compact('categories','ship_fee_temp','products_info')));
        });
    }

    public function upload_loop_img(Request $request) {
        $path_ret='/upload/'.date("YmdHis",time()).rand(1000,9999).".png";
        $img_path = public_path().$path_ret;
        Image::make(Input::file('photo'))->resize(750, null, function ($constraint) {
            $constraint->aspectRatio();
        })->save($img_path);
        return response()->success($path_ret);
    }

    public function edit_goods_handle(Request $request) {
        //var_dump($request->all());
        $all_params = $request->all();
        $product_name = $all_params['goods_name'];
        $category_id = $all_params['category'];
        $category_name = GoodsCategoriesService::getNameById($all_params['category']);
        $images = $all_params['loop_imgs'];
        $desc = $all_params['desc'];
        $promise = $all_params['promise'];
        $detail = $all_params['detail'];

        if(empty($product_name) || empty($category_id) || empty($images) ||empty($detail)||empty($promise)) {
            return response()->error('PARAM_EMPTY');
        }
        $pattern1 = "/<img.*?(?:>|\/>)/i";
        $pattern2 = "/src=[\'\"]?([^\'\"]*)[\'\"]?/i";
        $detail_arr = [];
        preg_match_all($pattern1,$detail,$matches);
        foreach($matches[0] as $match){
            preg_match($pattern2,$match,$matches2);
            #array_push($detail_arr,$matches2[1]);
            $detail_arr[] = $matches2[1];
        }
        $detail = implode(',',$detail_arr);
        $ship_fee_temp = $all_params['ship_fee_temp'];
        $thumb_img_input = public_path().(explode(',',$images)[0]);
        $path_ret='/upload/'.date("YmdHis",time()).rand(1000,9999).".png";
        $img_path = public_path().$path_ret;
        Image::make($thumb_img_input)->resize(350, null, function ($constraint) {
            $constraint->aspectRatio();
        })->save($img_path);
        $img_thum = $path_ret;
        $vip_month = $all_params['vip_month'];
        $product_data =compact('product_name','category_id','category_name','images','desc','promise','detail','ship_fee_temp','img_thum','vip_month');
        $goods_id=$all_params['goods_id'];
        DB::beginTransaction();
        try{
            if($all_params['goods_id']) {   //更新
                ProductsService::updateProduct($all_params['goods_id'],$product_data);
            }else{
                $product_info = ProductsService::addProduct($product_data);
                $goods_id = $product_info->id;
            }

            foreach ($all_params['goods_spec'] as $key=>$item) {
                $spec_data = [
                    'product_id'=>$goods_id,
                    'specification'=>$item,
                    'price'=>$all_params['price'][$key],
                    'origin_price'=>$all_params['market_price'][$key],
                    'cost'=>$all_params['cost'][$key],
                    'stock'=>$all_params['stock'][$key]
                ];
                if($all_params['goods_spec_id'][$key]) {
                    ProductsSpecifictionService::updateProductSpec($all_params['goods_spec_id'][$key],$spec_data);
                }else{
                    ProductsSpecifictionService::addProductSpec($spec_data);
                }
            }
            DB::commit();
        }catch (\Exception $e) {
            \Log::error($e->getMessage());
            DB::rollback();
            return response()->error('ADD_PRODUCT_FAILED');
        }
        return response()->success();
    }

    public function products_list(Request $request) {
        $goods_name = $request->input('goods_name','');
        $category_id = $request->input('category','');
        $goods_list = ProductsService::getProductsListDetail(compact('goods_name','category_id'));
        $categories = GoodsCategoriesService::getAll();
        return Admin::content(function (Content $content) use($request,$goods_list,$categories){

            $content->body(view("shop.goods_list",compact('goods_list','categories')));
        });
    }

    public function upload_detail_img(Request $request) {
        //var_dump($request->all());
        $imgs = $request->allFiles();
        $imgs_return = array();
        foreach ($imgs as $img) {
            $path = '/upload';
            $file_name = date("YmdHis",time()).rand(1000,9999).".png";
            $path_ret=$path.'/'.$file_name;
            $img_path = public_path().$path_ret;
            //Image::make($img)->save($img_path);
            $path_=$img->storeAs('upload',$file_name,'public');
            $imgs_return[] = env('APP_DOMAIN').$path_ret;
            //var_dump($path_);
        }
        return response()->json(['errno'=>0,'data'=>$imgs_return]);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function delete_products(Request $request) {
        $goods_id = $request->input('goods_id','');
        ProductsService::deleteProducts($goods_id);
        return response()->success();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function changeProductsStatus(Request $request) {
        $goods_id = $request->input('goods_id','');
        $status = $request->input('status',0);
        $products = ProductsService::getProductsDetailAll($goods_id);
        $products->status = $status;
        $products->save();
        return response()->success();
    }
}
